package com.zhaotianhao.controller;

import com.github.pagehelper.PageInfo;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;
import com.zhaotianhao.pojo.Cats;
import com.zhaotianhao.service.CatsService;
import com.zhaotianhao.util.FileUtils;
import com.zhaotianhao.util.PDFUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @Author Z-7
 * @Date 2022/3/1
 */
@Controller
@RequestMapping("cats")
public class CatsController {
    @DubboReference
    private CatsService catsService;
    @RequestMapping("list")
    public String to_list(@RequestParam(defaultValue = "1")int pageNum, @RequestParam(defaultValue = "3")int pageSize, Model model){
        PageInfo<Cats> page = catsService.queryByPage(null, pageNum, pageSize);
        model.addAttribute("page",page);
        return "cats/cats_list";
    }
    @RequestMapping("getCats")
    public @ResponseBody List<Cats> getCats(){
        return catsService.queryAll();
    }
    @RequestMapping("exportPDF")
    public void exportPDF(@RequestParam(defaultValue = "1")int pageNum, @RequestParam(defaultValue = "3")int pageSize, int mode, HttpServletResponse response) throws Exception {
        // 查询当前页所有的分类
        PageInfo<Cats> page = catsService.queryByPage(null, pageNum, pageSize);
        // 新建文档对象
        Document document = new Document();
        // 生成pdf文件名称
        String fileName = UUID.randomUUID().toString() + ".pdf";
        // 生成pdf文件实际地址
        PdfWriter writer = PDFUtils.createDoc(document, "d:/mypdf/" + fileName);
        // 创建容器
        List<String> list = new ArrayList<>();
        // 标题
        list.add("豪哥商城分类菜单");
        // pdf添加内容
        PDFUtils.addContent(document,list,18);
        // 创建表格以及数据
        PDFUtils.addTable(writer,new String[] {"分类编号","分类名称"},new String[] {"id","catName"},page.getList(),50,600);

        document.close();
        writer.close();

        // 添加图片水印
        PDFUtils.markImage("g:/img/323696.jpg",new FileInputStream("d:/mypdf/"+fileName),new FileOutputStream("d:/mypdf1/"+fileName),"版权所有");
        // 下载这个文件
        FileUtils.download(response,"d:/mypdf1/"+fileName,"豪哥商城分类.pdf",mode);
    }
}
